package com.yuan.base.framework;

import android.content.DialogInterface;
import android.os.Looper;
import android.support.v7.app.AlertDialog;

import com.umeng.analytics.MobclickAgent;
import com.yuan.base.utils.ActivityManager;

import java.lang.Thread.UncaughtExceptionHandler;


/**
 * 全局的异常处理类
 */
public class BaseCrashHandler implements UncaughtExceptionHandler {

	public static final String TAG = BaseCrashHandler.class.getSimpleName();

	private static BaseCrashHandler INSTANCE = new BaseCrashHandler();

	// 计数器,防止线程异常后循环卡死的现象
	private static int count = 0;

	private BaseCrashHandler() {
	}

	public static BaseCrashHandler getInstance() {
		return INSTANCE;
	}

	public void init() {
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread thread, final Throwable ex) {
		ex.printStackTrace();
		count++;
		if (count > 2) {
			return;
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				Looper.prepare();
				if (ActivityManager.getInstance().currentActivity() != null) {
					MobclickAgent.reportError(ActivityManager.getInstance().currentActivity(), ex);
					new AlertDialog.Builder(ActivityManager.getInstance().currentActivity()).setIcon(android.R.drawable.ic_dialog_info).setTitle("错误")
							.setMessage("系统出现错误，需要退出！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							count = 0;
							dialog.dismiss();
							ActivityManager.getInstance().popAllActivity();
							// 干掉当前的程序
							android.os.Process.killProcess(android.os.Process.myPid());
							System.exit(0);
						}
					}).create().show();
				}
				Looper.loop();
			}
		}).start();
	}
}
